<?php

namespace App\Http\Controllers;

use App\Availability;
use App\Order;
use App\RoomType;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AvailabilityController extends Controller
{
    // get available roomTypes and their remain counts between $begin and $end
    private function getRoomTypeRmain($begin, $end, $except=null): Collection{
        $reserved = Availability::query()
            ->select(DB::raw('room_type_id, count(*) as reserved'))
            ->whereRaw('(`from` between ? and ? or `to` between ? and ? or
             ? between `from` and `to` or ? between `from` and `to` )',
                [$begin, $end, $begin, $end, $begin, $end]
            )->where('is_valid', true);
        if($except !== null){
            $reserved = $reserved->where('id', '!=', $except);
        }
        $reserved = $reserved
            ->groupBy('room_type_id')
            ->get()
            ->keyBy('room_type_id');
        $roomtypes = RoomType::query()->withCount('rooms')->get();
        //计算剩余房间数量
        foreach ($roomtypes as $roomtype){
            if($reserved->has($roomtype->id)){
                $roomtype->rooms_count -= $reserved[$roomtype->id]->reserved;
            }
        }
        //过滤掉剩余数量为零的房间类型
        $roomtypes = $roomtypes->reject(static function($roomtype){
            return $roomtype->rooms_count === 0;
        });
        return $roomtypes;
    }

    // add 'order' in request param to reject that order's
    // availability information
    public function searchRoomType(Request $request){
        $begin = $request->get('begin');
        $end = $request->get('end');
        // $counts = [];
        if($request->has('order')) {
            $order_id = $request->get('order');
            $order = Order::findOrFail($order_id);
            $counts = $this->getRoomTypeRmain($begin, $end, $order->availability->id);
        } else {
            $counts = $this->getRoomTypeRmain($begin, $end);
        }
        return response()->json([
            'full' => $counts->isEmpty(),
            'types' => $counts,
        ]);
    }
}
